<template>
  <div class="app-container">
    <!--    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工位编号" prop="siteId">
        <el-input v-model="queryParams.siteId" placeholder="请输入工位编号" clearable size="small" />
      </el-form-item>
      <el-form-item label="工位名称" prop="siteName">
        <el-input v-model="queryParams.siteName" placeholder="请输入工位名称" clearable size="small" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" >搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" >重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <!--    <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:bom:add']"
        >新增</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table :data="siteList">
      <el-table-column label="ID" align="center" prop="id" v-if="false" />
      <el-table-column label="工位编号" align="center" prop="siteId" width="100" />
      <el-table-column label="工位名称" align="center" prop="siteName" width="200" />
      <el-table-column label="工位IP" align="center" prop="opcUrl" width="180" />
      <el-table-column label="工位图片" width="180">

        <template slot-scope="scope">

          <el-image style="width: 80px; height: 80px" :src="scope.row.siteImg"
            :preview-src-list="getImgList(scope.row.siteImg)">
            <div slot="error" class="image-slot">

            </div>
          </el-image>
        </template>

      </el-table-column>
      <el-table-column label="连接" width="55">
        <template slot-scope="scope">
          <el-button :type="scope.row.conState=='1'?'success':'danger'" circle></el-button>
        </template>

      </el-table-column>
      <el-table-column label="模式">
        <template slot-scope="scope" width="55">
          <el-button :type="scope.row.mesState=='true'?'success':'danger'" circle></el-button>
        </template>
      </el-table-column>
    </el-table>

  </div>
</template>

<script>
  import {

    siteListOfPro,
    siteState

  } from "@/api/mes/site_mon";

  import mqtt from 'mqtt';

  export default {
    name: "site_mon",
    components: {

    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {

        },
        // 工位表格数据
        siteList: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        mqtt_client: null,
        mqtt_options: {
          clean: true, // true: 清除会话, false: 保留会话
          connectTimeout: 4000, // 超时时间
          // 认证信息
          clientId: 'emqx_web',
          username: 'emqx_web',
          password: 'emqx_web',
        }
      };
    },
    created() {

      this.initMqtt();
      this.getList();

      // this.initWebSocket();

    },
    destroyed() {
      this.mqtt_client.end() //离开路由之后断开websocket连接
    },
    methods: {
      getImgList(img) {
        let images = new Array();
        images.push(img);
        return images;

      },
      getList() {
        siteListOfPro().then(res => {
          //  console.log(res);
          this.siteList = res.rows;
          this.loading = false;

          let msg = {
            "station": "gw01",
            "nodes": [{
              "id": 'ns=3;s="OPC"."To_MES"."mes_mode"'
            }]
          }
          this.mqtt_client.publish('to/station/read', JSON.stringify(msg))

          msg = {
            "station": "gw02",
            "nodes": [{
              "id": 'ns=4;i=16'
            }]
          }
          this.mqtt_client.publish('to/station/read', JSON.stringify(msg))
          msg = {
            "station": "gw03",
            "nodes": [{
              "id": 'ns=4;i=16'
            }]
          }
          this.mqtt_client.publish('to/station/read', JSON.stringify(msg))
          msg = {
            "station": "gw04",
            "nodes": [{
              "id": 'ns=4;i=16'
            }]
          }
          this.mqtt_client.publish('to/station/read', JSON.stringify(msg))
          msg = {
            "station": "gw05",
            "nodes": [{
              "id": 'ns=4;i=16'
            }]
          }
          this.mqtt_client.publish('to/station/read', JSON.stringify(msg))
          msg = {
            "station": "gw06",
            "nodes": [{
              "id": 'ns=4;i=16'
            }]
          }
          this.mqtt_client.publish('to/station/read', JSON.stringify(msg))

        });

      },

      async getState(gw) {
        let typeStr = "";
        await siteState(gw).then(res => {
          if (res.data[gw] == "0") {
            typeStr = "danger"
          }
          if (res.data[gw] == "1") {
            typeStr = "success"
          }

        });
        //  console.log(typeStr)
        return typeStr
      },
      judgeState(row) {
        this.getState(row.siteId).then(res => {
          return res
        })
        // console.log(this.getState(row.siteId));
        // return this.getState(row.siteId)
      },
      //websocket

      // initWebSocket() { //初始化weosocket
      //   const wsuri = "ws://localhost:8080/ws/state_page";
      //   this.websock = new WebSocket(wsuri);
      //   this.websock.onmessage = this.websocketonmessage;
      //   this.websock.onopen = this.websocketonopen;
      //   this.websock.onerror = this.websocketonerror;
      //   this.websock.onclose = this.websocketclose;
      //   console.log("初始化weosocket")
      // },
      // websocketonopen() { //连接建立之后执行send方法发送数据

      //   console.log('连接成功');
      // },
      // websocketonerror() { //连接建立失败重连
      //   this.initWebSocket();
      // },
      // websocketonmessage(e) { //数据接收
      //   //const redata = JSON.parse(e.data);
      //   console.log(e.data)
      //   if (e.data == "refresh") {
      //     //刷新数据
      //     this.getList();
      //   }
      // },
      // websocketsend(Data) { //数据发送
      //   this.websock.send(Data);
      // },
      // websocketclose(e) { //关闭
      //   console.log('断开连接', e);
      // },

      initMqtt() {
        var that = this;
        that.mqtt_client = mqtt.connect("ws://39.106.111.79:8083/mqtt", this.mqtt_options);
        that.mqtt_client.on('connect', function() {
          that.mqtt_client.subscribe('from/station/state', function(err) {
          })

        })


        that.mqtt_client.on('message', function(topic, message) {
          var jsonMsg = JSON.parse(message.toString());
          //console.log(jsonMsg)
          // console.log(jsonMsg.data)


          switch (jsonMsg.data) {
            case "16":
              // console.log("MES模式")
              console.log(jsonMsg.station + "mes模式：" + jsonMsg.value)
              that.judgeGwState(jsonMsg.station, jsonMsg.value)
              break;

            case '"OPC"."To_MES"."mes_mode"':
              console.log(jsonMsg.station + "mes模式：" + jsonMsg.value)
              //console.log(jsonMsg)
              that.judgeGwState(jsonMsg.station, jsonMsg.value)
              break;

          }

        })


      },
      judgeGwState(gw, mesState) {
        var that = this;
        that.siteList.forEach(function(v, i) {
          if (v.siteId == gw) {
            that.siteList[i].conState = "1";
            console.log(mesState)
            that.siteList[i].mesState = mesState;
          }
        })

      }


    }
  };
</script>
